package com.gaogzhen.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @version 1.0
 * @description 实名认证
 * @date 2022-07-26 11:29
 */
@Configuration
@EnableConfigurationProperties(IdProperties.class)
public class IdAutoConfiguration {

    private static IdProperties idProperties;

    private static final RestTemplate REST_TEMPLATE = new RestTemplate();

    public IdAutoConfiguration(IdProperties idProperties) {
        IdAutoConfiguration.idProperties = idProperties;
    }

    /**
     * 实名认证
     * @param realName  真实姓名
     * @param cardNum   身份证号
     * @return
     */
    public static boolean identify(String realName, String cardNum) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set(HttpHeaders.AUTHORIZATION, "APPCODE " + idProperties.getAppCode());


        ResponseEntity<String> entity = REST_TEMPLATE.exchange(String.format(idProperties.getUrl(), realName, cardNum), HttpMethod.POST, new HttpEntity<>(null, httpHeaders), String.class);
        if (entity.getStatusCode() == HttpStatus.OK) {
            String body1 = entity.getBody();
            JSONObject jsonObject = JSON.parseObject(body1);
            String code = jsonObject.getString("code");
            return StringUtils.equals("0", code);
        }
        return false;
    }
}
